<script setup>

import {mySiderBarIcon, cardVideoStatusIcon, videoBottomIcons} from "@/views/NewScreenShare/Asset.js";
import {useDisplayMedia} from "@vueuse/core";
import {UseSocketStore, UseUserStore} from "@/stores/index";
import {useRouter} from 'vue-router'
import {v4 as uuid} from 'uuid';

// import {joinRooms} from "@/views/NewScreenShare/page/CardBody/UseVideoShare.js";
// 头像
import {avator} from '@/views/NewScreenShare/Asset.js'
import {message} from "ant-design-vue";

let userStore = UseUserStore()
let store = UseSocketStore()
let router = useRouter()
let videoRef = ref(null)
let otherVideoRef = ref(null)
const {stream, start} = useDisplayMedia();

// root权限是否开启了直播 其他用户/显示什么视图- 0是没直播 1是是否同意加入
const isotherPeopleAcceptMeettingView = ref(0)
// 已经连接成功,隐藏一些控件 0是没连接 1是连接成功
let isConnectedVideoStream = ref(0)
// 获取用户信息
let userName = userStore.userInfo.userName ? userStore.userInfo.userName : router.push('/home')
const userInfo = ref({
  userName,
  id: uuid(),
  role: userName === 'root' ? 'root' : 'user',
  roomId: userStore.userInfo.roomId,
  avator: avator[Math.floor(Math.random() * 6)]
})
userStore.userInfo = userInfo.value

function commonInfo() {
  return {
    roomId: userStore.userInfo.roomId,
    userId: userStore.userInfo.id,
  }
}

// 初始化socket
store.initSocketConnect(userInfo.value)
// 加入房间
store.joinRooms(userInfo.value)

// rtc信息
let peer = ref(null)
let localStream = ref(null)
let remoteStream = ref(null)
let peerConfig = {iceServers: [{urls: "stun:stun.l.google.com:19302"}], sdpSemantics: 'plan-b'};
// 本地
let localOffer = ref(null)
let localAnswer = ref(null)
let localCandidate = ref(null)

function resetRtc() {
  peer.value?.close()
  peer.value = null
  stream.value = null
  localStream.value = null
  remoteStream.value = null
  videoRef.value = null
  otherVideoRef.value = null
}


watchEffect(() => {
  // preview on a video element
  store.userInfo = userInfo.value
  if (videoRef.value && stream.value) {
    // 设置video流
    setVideoVal()
  }


  // 开始邀请参与
  store.socket.on('callRemote', (data) => {
    console.log('收到邀请', data)
    if (data.code === 200) {
      message.success(data.message)
      isotherPeopleAcceptMeettingView.value = 1
    }
  })

  // 同意邀请
  store.socket.on('acceptCall', async (data) => {
    console.log('收到同意邀请', data)
    if (data.code === 200 && data.userId !== userInfo.value.id) {
      message.success(data.message)

      // 创建offer
      createPeerConnection()

      // 添加本地流
      if (stream.value) {
        stream.value.getTracks().forEach(track => {
          peer.value.addTrack(track, stream.value);
        });
      } else {
        console.error('stream.value is undefined or null');
      }
      // 生成offer
      const offer = await peer.value.createOffer({
        offerToReceiveAudio: 1,
        offerToReceiveVideo: 1
      })

      console.log(offer)
      // 设置本地描述的offer
      peer.value.setLocalDescription(offer);

      // 发送给对方
      // 通过信令服务器将offer发送给用户B
      store.socket?.emit('sendOffer', {
        offer,
        ...commonInfo()
      })
    }
  })
})

// 接收offer
store.socket.on('receiveOffer', async (data) => {
  if (data.code === 200 && userStore.userInfo.role !== 'root') {
    console.log('收到offer', data)
    message.success(data.message)
    createPeerConnection()
    // 先把offer设置为远端
    peer.value.setRemoteDescription(data.offer);
    // 创建answer
    const answer = await peer.value.createAnswer();
    // 把answer设置本地
    if (!answer) return
    await peer.value.setLocalDescription(answer);
    // 发送answer
    store.socket?.emit('sendAnswer', {answer, ...commonInfo()});

    peer.value.onicecandidate = (event) => {
      if (event.candidate) {
        console.log('发送answer那一方的candidate信息', event.candidate);
        store.socket?.emit('sendCandidate', {...commonInfo(), candidate: event.candidate});
      }
    };
  }
})
// 接收answer
store.socket.on('receiveAnswer', async (data) => {
  // 只有开启会议的才能收到answer
  if (data.code === 200 && userStore.userInfo.role === 'root') {
    console.log('收到answer', data)
    message.success(data.message)
    createPeerConnection()
    if (data.answer) {
      peer.value.setRemoteDescription(data.answer).then(() => {
        console.log('添加answer成功')
      })

      //发送offer那一方 监听icecandidate事件
      peer.value.onicecandidate = (event) => {
        console.log('准备获取主持人的candidate信息')
        if (event.candidate) {
          console.log('获取主持人的candidate信息', event.candidate);
          store.socket?.emit('sendCandidate', {...commonInfo(), candidate: event.candidate});
        }
      };

      store.socket?.on('receiveCandidate', async (data) => {
        console.log('接收到candidate', data.candidate);
        // 设置远程描述的candidate
        peer.value.addIceCandidate(data.candidate).then(res => {
          console.log('添加candidate成功', res)
        })
      })
    }
  }
})

function createPeerConnection() {

  //如果是多人的话，在这里要创建一个新的连接.
  //新创建好的要放到一个map表中。
  //key=userid, value=peerconnection
  console.log('create RTCPeerConnection!');
  if (!peer.value) {
    peer.value = new RTCPeerConnection(peerConfig);
    console.log('peer.value', peer.value)
    peer.value.onicecandidate = (event) => {

      if (event.candidate) {
        store.socket?.emit('sendCandidate', {...commonInfo(), candidate: event.candidate});
      } else {
        console.log('this is the end candidate');
      }
    }

    peer.value.ontrack = function (e) {
      if (e.streams) {
        otherVideoRef.value.srcObject = e.streams[0];
        remoteStream.value = e.streams[0]
        isConnectedVideoStream.value = 1
      }
    };
  } else {
    console.log('the pc have be created!');
  }

  return;
}

// 同意添加会议
function otherPeopleAcceptMeetting() {
  store.socket.emit('acceptCall', {
    ...commonInfo(),
    message: '同意加入会议'
  });
}

// 拒绝添加会议
function otherPeopleRefuseMeetting() {
  store.socket.emit('refuseCall', {
    ...commonInfo(),
    message: '拒绝加入会议'
  })
}

// 设置video流
function setVideoVal() {
  videoRef.value.srcObject = stream.value
  localStream.value = stream.value
}

// 开始会议
function startMeeting() {
  if (userStore.userInfo.role !== 'root') {
    message.error('您没有权限开始会议');
    return
  }
  message.success('开启会议成功');
  start();

  store.socket?.emit('callRemote', {
    ...commonInfo(),
    message: '开始会议,邀请对方参加会议'
  });
}

function endMeeting() {
  isConnectedVideoStream.value = 0
  isotherPeopleAcceptMeettingView.value = 0
  console.log('endMeeting')
  resetRtc()

}

function checkMeeting() {
  createPeerConnection()

}
</script>

<template>
  <div v-if="userStore.userInfo.role==='root'" id="bodyBox" class="w-full h-full">
    <div class="m-2 relative h-full">
      <video id="localVideo" ref="videoRef" autoplay="autoplay" class="w-full  rounded-3xl"
             poster="https://pic2.zhimg.com/80/v2-3afad658b44f596b10ec13b2b6d4299d_1440w.webp">
      </video>
      <!--            图标-->
      <div class="absolute bottom-3.5  left-1/2 transform -translate-x-1/2">
        <div class="flex items-center pt-10 ">
          <div v-for="item in cardVideoStatusIcon" :key="item"
               class="m-2 w-10 h-10 pt-0.5  leading-10 rounded-full bg-gray-200 text-center hover:bg-blue-500 *:hover:text-white   transition-all  ease-in-out delay-80">
            <span :class="item" class="textNoActiveStyle group-hover:text-white"></span>
          </div>
          <div
              class="m-2 w-20 h-10 pt-0.5  leading-10 rounded-full bg-gray-200 text-center hover:bg-red-500 *:hover:text-white   transition-all  ease-in-out delay-80">
            <span class="icon-[bi--telephone-fill] icon-[bi--telephone]textNoActiveStyle group-hover:text-white"></span>
          </div>
        </div>
      </div>
    </div>
    <!--       底部 图标-->
    <div class="flex  justify-center  space-x-8 ">
      <a-button class="btnStyle startButton" type="primary" @click="startMeeting">
        开始会议
      </a-button>
      <a-button class="btnStyle startButton" danger type="primary" @click="endMeeting">结束会议</a-button>
      <div v-for="item in videoBottomIcons" :key="item"
           class="m-2 w-10 h-10 pt-0.5  leading-10 rounded-full bg-gray-200 text-center hover:bg-blue-500 *:hover:text-white   transition-all  ease-in-out delay-80">

        <a-tooltip placement="bottom">
          <template #title>
            <span>{{ item.label }}</span>
          </template>
          <span :class="item.icon" class=" textNoActiveStyle group-hover:text-white"></span>
        </a-tooltip>

      </div>
    </div>
  </div>


  <div v-else id="bodyBox" class="w-full h-full">
    <div class="m-2 relative h-full">
      <!--  其他人的-->
      <video id="otherVideo" ref="otherVideoRef" autoplay="autoplay" class="w-full  rounded-3xl bg-black"
             poster="">
      </video>

      <template v-if="isConnectedVideoStream===0">
        <!--      没人直播和加入直播-->
        <div v-if="isotherPeopleAcceptMeettingView === 1 "
             class="absolute w-full  bottom-1/3" style="margin: 0 auto">
          <div class=" h-2/5   flex justify-center text-center w-full">
            <img class="w-1/5" src="./暂无消息.png">
          </div>
          <div>
            <p class="text-white text-center mb-4">有正在进行的会议哦~</p>
          </div>
          <div class=" flex justify-center text-center w-full">
            <a-button class="h-12 w-2/5  text-xs startButton" type="primary" @click="otherPeopleAcceptMeetting">加入直播
            </a-button>
          </div>
        </div>

        <div v-else-if="isotherPeopleAcceptMeettingView===0" class="absolute w-full"
             style="margin: 0 auto;bottom: 40%">
          <div class=" h-2/5   flex justify-center text-center w-full">
            <img class="w-1/5" src="./正在进行的会议.png ">
          </div>
          <div>
            <p class="text-white text-center mb-4">暂时没有进行的会议哦~</p>
          </div>
        </div>
      </template>

      <!--            图标-->
      <div class="absolute bottom-3.5  left-1/2 transform -translate-x-1/2">
        <div class="flex items-center pt-10 ">
          <div v-for="item in cardVideoStatusIcon" :key="item"
               class="m-2 w-10 h-10 pt-0.5  leading-10 rounded-full bg-gray-200 text-center hover:bg-blue-500 *:hover:text-white   transition-all  ease-in-out delay-80">
            <span :class="item" class="textNoActiveStyle group-hover:text-white"></span>
          </div>
          <div
              class="m-2 w-20 h-10 pt-0.5  leading-10 rounded-full bg-gray-200 text-center hover:bg-red-500 *:hover:text-white   transition-all  ease-in-out delay-80">
            <span class="icon-[bi--telephone-fill] icon-[bi--telephone]textNoActiveStyle group-hover:text-white"></span>
          </div>
        </div>
      </div>
    </div>
    <!--       底部 图标-->
    <div class="flex  justify-center  space-x-8 ">
      <a-button class="btnStyle startButton" type="primary" @click="checkMeeting">
        更新状态
      </a-button>
      <a-button class="btnStyle startButton" danger type="primary" @click="endMeeting">结束会议</a-button>
      <div v-for="item in videoBottomIcons" :key="item"
           class="m-2 w-10 h-10 pt-0.5  leading-10 rounded-full bg-gray-200 text-center hover:bg-blue-500 *:hover:text-white   transition-all  ease-in-out delay-80">

        <a-tooltip placement="bottom">
          <template #title>
            <span>{{ item.label }}</span>
          </template>
          <span :class="item.icon" class=" textNoActiveStyle group-hover:text-white"></span>
        </a-tooltip>

      </div>
    </div>
  </div>
</template>
<!--//bg-indigo-500 h-0.5 leading-.25-->
<style lang="scss" scoped>

video {
  height: 88% !important;
}

.btnStyle {
  @apply mt-1 max-w-xl h-12   text-sm text-center
}

@media screen and (max-width: 512px) {
  .startButton {
    line-height: 0.2rem;
    height: 0.2rem;
    //background-color: #1f2d3d;
  }
}
</style>